export const getCurrentDayTimestamp = () => {
  return new Date(new Date().toLocaleDateString()).valueOf()
}

// @return 2021-08-30
export const getCurrentDate = (differ = 0) => {
  const date = new Date(getCurrentDayTimestamp() + differ)
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  return `${year}-${month}-${day}`
}

export const formatMoney = function (val, w = 2) {
  // 金额转换 分->元 保留2位小数 并每隔3位用逗号分开 1,234.56
  const str = (val / 1).toFixed(w) + ''
  const intSum = str.substring(0, str.indexOf('.')).replace(/\B(?=(?:\d{3})+$)/g, ',')// 取到整数部分
  const dot = str.substring(str.length, str.indexOf('.'))// 取到小数部分搜索
  const ret = intSum + dot
  return ret
}

/**
 *
 * @param {*} date 2021-10-21
 * @returns 10/21/2021 月日年
 */
export const convertDate = function (date, separator = '-', expectSeparator = '/') {
  if (!date) {
    console.error('[Date] 为空')
    return ''
  }
  const list = date.split(separator)
  const result = []
  result.push(list[1])
  result.push(list[2])
  result.push(list[0])

  const resultStr = result.join(expectSeparator)

  return resultStr
}

/**
 *
 * @param {*} list [{ name:'', data: [{}] }]
 * @returns
 */
export const floatList = (list) => {
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    const { data } = item
    item.data = _float(data)
  }
  return list
}

export const _float = (data) => {
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    Object.keys(item).forEach(key => {
      const val = item[key]
      if (val && Object.prototype.toString.call(val) === '[object Object]') {
        Object.keys(val).forEach(_key => {
          const newKey = `${key}.${_key}`
          const _val = val[_key]
          item[newKey] = _val
        })
      }
    })
  }
  return data
}

export const addTotal = (data) => {
  if (!data || !data.length) return
  const total = {}
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    Object.keys(item).forEach(key => {
      const val = item[key]
      if (typeof val === 'number' || Number(val)) {
        if (!total[key]) {
          total[key] = val
        } else {
          total[key] = Number(total[key]) + Number(val)
        }
      }
    })
    item.total = total
  }
  return data
}
